package com.dg.service.impl;

import com.dg.common.PageQuery;
import com.dg.common.PageResult;
import com.dg.dao.DeptMapper;
import com.dg.dao.RoleMapper;
import com.dg.dao.RoleUserMapper;
import com.dg.dao.UserMapper;
import com.dg.dto.UserDto;
import com.dg.dto.UserTransferDto;
import com.dg.exception.ParamException;
import com.dg.param.LoginParam;
import com.dg.param.UserParam;
import com.dg.pojo.Dept;
import com.dg.pojo.Role;
import com.dg.pojo.User;
import com.dg.service.UserService;
import com.dg.util.ValidatorUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;

/**
 * @author mrq
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private RoleUserMapper roleUserMapper;
    @Autowired
    private RoleMapper roleMapper;


    @Override
    public User login(LoginParam param){
        ValidatorUtil.validate(param);
        if(!checkExist(null, param.getUsername())){
            throw new ParamException("该用户不存在");
        }
        User  user= userMapper.login(param.getUsername(), param.getPassword());
        return user;
    }

    @Override
    public PageResult<UserDto> list(Integer deptId, PageQuery pageQuery) {
        ValidatorUtil.validate(pageQuery);
        int count = userMapper.countByDeptId(deptId);
        List<User> list=userMapper.getAllOrByDeptId(deptId, pageQuery);
        if(CollectionUtils.isEmpty(list)){
            return PageResult.<UserDto>builder().total(count).data(Lists.newArrayList()).build();
        }
        List<UserDto> userDtoList = Lists.newArrayList();
        for (User user : list){
            UserDto dto = UserDto.adapt(user);
            Dept dept = deptMapper.selectByPrimaryKey(user.getDeptId());
            dto.setDeptName(dept.getName());
            List<Integer> roleIdList = roleUserMapper.getRoleIdListByUserId(user.getId());
            if(CollectionUtils.isNotEmpty(roleIdList)){
                List<Role> roleList = roleMapper.getRoleListByRoleIdList(roleIdList);
                StringBuilder roles = new StringBuilder();
                for (int i=0;i < roleList.size();i++){
                    roles.append(roleList.get(i).getName());
                    if(i != roleList.size() - 1){
                        roles.append(',');
                    }
                }
                dto.setRoles(roles.toString());
            }
            userDtoList.add(dto);
        }
        return PageResult.<UserDto>builder().total(count).data(userDtoList).build();
    }

    @Override
    public void save(UserParam param) {
        ValidatorUtil.validate(param);
        if(checkExist(param.getId(), param.getUsername())){
            throw new ParamException("用户名已存在");
        }
        User user = User.builder().username(param.getUsername()).
                phone(param.getPhone()).password(param.getPassword()).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark())
                .operator("admin").operateIp("127.0.0.1").operateTime(new Date()).build();
        userMapper.insertSelective(user);
    }

    @Override
    public void update(UserParam param){
        ValidatorUtil.validate(param);
        if(!checkExist(param.getId(), param.getUsername())){
            throw new ParamException("用户名已存在");
        }
        User user = User.builder().id(param.getId()).username(param.getUsername()).remark(param.getRemark())
                .operator("admin").operateIp("127.0.0.1").operateTime(new Date()).build();
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void delete(Integer id) {
        if(id == null){
            throw new ParamException("id不能为空");
        }
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<UserTransferDto> getAll() {
        List<User> userList = userMapper.getAll();
        List<UserTransferDto> userTransferDtoList = Lists.newArrayList();
        for (User user : userList){
            UserTransferDto dto = UserTransferDto.adapter(user);
            userTransferDtoList.add(dto);
        }
        return userTransferDtoList;
    }


    private boolean checkExist(Integer id, String name) {
        return userMapper.findByName(id,name) > 0;
    }


}
